package top.topsmart.api.bycenter.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import top.topsmart.api.bycenter.entity.view.CommitView;
import top.topsmart.api.bycenter.entity.view.DynamicView;
import top.topsmart.api.bycenter.mapper.DynamicMapper;
import top.topsmart.api.bycenter.mapper.InfoMapper;
import top.topsmart.api.bycenter.mapper.UserMapper;
import top.topsmart.api.bycenter.mapper.UserOperationMapper;
import top.topsmart.api.bycenter.model.Dynamic;
import top.topsmart.api.bycenter.model.Info;
import top.topsmart.api.bycenter.model.User;
import top.topsmart.api.bycenter.entity.pojo.MineEntity;
import top.topsmart.api.bycenter.model.UserOperation;
import top.topsmart.api.bycenter.service.WechatService;
import top.topsmart.api.bycenter.util.RequestGet;
import top.topsmart.api.bycenter.util.Result;
import top.topsmart.api.bycenter.util.TimeHandler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WechatServiceImpl implements WechatService {
    @Autowired
    private WechatServiceImpl that;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private InfoMapper infoMapper;
    @Autowired
    private UserOperationMapper userOperationMapper;
    @Autowired
    private DynamicMapper dynamicMapper;

    @Value("${wechat.appid}")
    private String APPID;
    @Value("${wechat.secret}")
    private String SECRET;

    //第一步 对调用微信官方HTTP API返回的结果处理 拿到openid
    public Result code2session(String code) throws Exception {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+"&secret="+SECRET+"&" +
                "js_code="+code+"&grant_type=authorization_code";
        JSONObject session = new RequestGet().send(url);
        //一般情况
        if(session.getInteger("errcode") == null){
            return new Result(0,session);
        } else {
            return new Result(1501,"调用微信接口出错",session);
        }
    }

    //第二步 判断新旧用户
    public Result isUser(Result param) throws Exception {
        //一般情况
        String openid = param.getData().getString("openid");
        User resUser = userMapper.selectByOpenid(openid);
        if (resUser == null){
            JSONObject data = new JSONObject();
            data.put("isUser",false);
            data.put("openid",openid);
            return new Result(0,data);
        } else {
            JSONObject data = new JSONObject();
            data.put("isUser",true);
            data.put("user",resUser);
            data.put("openid",openid);
            return new Result(0,data);
        }
    }
    //第四步
    public Result backUser(Result param) throws Exception {
        //老用户
        if(param.getData().getBoolean("isUser")){
            JSONObject data = new JSONObject();

            User user = param.getData().getObject("user",User.class);
            String id = user.getId();

            double a = (new Date().getTime() - user.getRegTime().getTime());
            double b = a/86400000;
            double day = Math.ceil(b);

            Info info = infoMapper.selectByPrimaryKey(user.getInfoId());

            data.put("user",user); //
            data.put("day",day); //
            data.put("avatar",info.getAvatar()); //
            data.put("nickname",info.getNickname()); //
            data.put("fans",userOperationMapper.getMine(new MineEntity(id,"fans")));
            data.put("follows",userOperationMapper.getMine(new MineEntity(id,"follows")));
            data.put("loves",userOperationMapper.getMine(new MineEntity(id,"loves")));
            data.put("commits",userOperationMapper.getMine(new MineEntity(id,"commits")));
            data.put("dynamics",dynamicMapper.getMine(new MineEntity(id,"dynamics")));
            return new Result(0,"success",data);
        } else {
            //新用户
            String id = UUID.randomUUID().toString();
            User newUser = new User(
                     id
                    ,param.getData().getString("openid")
                    ,infoMapper.randomBack(1).get(0).getId()
                    ,1
                    ,true
                    ,false
                    );
            userMapper.insert(newUser);

            JSONObject data = new JSONObject();
            User user = userMapper.selectByOpenid(param.getData().getString("openid"));
            double a = (new Date().getTime() - user.getRegTime().getTime());
            double b = a/86400000;
            double day = Math.ceil(b);
            Info info = infoMapper.selectByPrimaryKey(user.getInfoId());

            data.put("user",user); //
            data.put("day",day); //
            data.put("avatar",info.getAvatar()); //
            data.put("nickname",info.getNickname()); //
            data.put("fans",userOperationMapper.getMine(new MineEntity(id,"fans")));
            data.put("follows",userOperationMapper.getMine(new MineEntity(id,"follows")));
            data.put("loves",userOperationMapper.getMine(new MineEntity(id,"loves")));
            data.put("commits",userOperationMapper.getMine(new MineEntity(id,"commits")));
            data.put("dynamics",dynamicMapper.getMine(new MineEntity(id,"dynamics")));
            return new Result(0,"success",data);
        }
    }

    @Override
    public Result login(String code) throws Exception {
        Result res = that.code2session(code);
        if (res.getCode() == 0){
           return that.backUser(that.isUser(res));
        } else {
            return res;
        }
    }

    @Override
    public Result reload(String id) {
        JSONObject data = new JSONObject();

        User user = userMapper.selectByPrimaryKey(id);

        double a = (new Date().getTime() - user.getRegTime().getTime());
        double b = a/86400000;
        double day = Math.ceil(b);

        Info info = infoMapper.selectByPrimaryKey(user.getInfoId());

        List<Dynamic> dynamics = dynamicMapper.getMine(new MineEntity(id,"dynamics"));
        List<DynamicView> dynamicViews = new ArrayList<DynamicView>();
        for (int i = 0 ; i < dynamics.size() ; i++){
            Dynamic dynamic = dynamics.get(i);
            DynamicView dynamicView = new DynamicView();

            UserOperation SParam_loves = new UserOperation();
            SParam_loves.setObject(dynamic.getId());
            Integer loves = userOperationMapper.getLoves(SParam_loves).size();
            UserOperation SParam_commits = new UserOperation();
            SParam_commits.setObject(dynamic.getId());
            Integer commits = userOperationMapper.getCommits(SParam_commits).size();

            dynamicView.setId(dynamic.getId());
            dynamicView.setPublisher(dynamic.getPublisher());
            dynamicView.setArea(dynamic.getArea());
            dynamicView.setAvatar(info.getAvatar());
            dynamicView.setNickname(info.getNickname());
            dynamicView.setLevel(user.getLevel());
            dynamicView.setMood(dynamic.getMood());
            dynamicView.setContent(dynamic.getContent());
            dynamicView.setImage(dynamic.getImage());
            dynamicView.setVideo(dynamic.getVideo());
            dynamicView.setDevice(dynamic.getDevice());
            dynamicView.setReleaseTime(new TimeHandler().TimeHandler(dynamic.getReleaseTime()));
            dynamicView.setViews(dynamic.getViews());
            dynamicView.setLoves(loves);
            dynamicView.setCommits(commits);
            //追加进去数组
            dynamicViews.add(dynamicView);
        }

        List<CommitView> commitViews = new ArrayList<CommitView>();
        List<UserOperation> commits = userOperationMapper.getMine(new MineEntity(id,"commits"));
        for (int i = 0; i<commits.size();i++){

            CommitView commitView = new CommitView();
            UserOperation commit = commits.get(i);

            Dynamic dynamic = dynamicMapper.selectByPrimaryKey(commit.getObject());
            User user1 = userMapper.selectByPrimaryKey(dynamic.getPublisher());
            Info info1 = infoMapper.selectByPrimaryKey(user1.getInfoId());
            commitView.setAvatar(info1.getAvatar());
            commitView.setNickName(info1.getNickname());
            commitView.setLevel(user1.getLevel());
            commitView.setContent(dynamic.getContent());
            commitView.setCommit(commit.getContent());
            commitView.setOperationId(commit.getId());
            commitViews.add(commitView);
        }

        data.put("user",user); //
        data.put("day",day); //
        data.put("avatar",info.getAvatar()); //
        data.put("nickname",info.getNickname()); //
        data.put("fans",userOperationMapper.getMine(new MineEntity(id,"fans")));
        data.put("follows",userOperationMapper.getMine(new MineEntity(id,"follows")));
        data.put("loves",userOperationMapper.getMine(new MineEntity(id,"loves")));
        data.put("commits",commitViews);
        data.put("dynamics",dynamicViews);
        return new Result(0,"success",data);
    }

    @Override
    public Info getInfo(String id) {
        return infoMapper.selectByPrimaryKey(id);
    }
}
